<template>
  <div class="page-modal">
    <el-dialog
      title="新建用户"
      width="30%"
      center
      destroy-on-close
      v-model="dialogVisible"
    >
      <CkyForm v-bind="modalConfig" v-model="formData"></CkyForm>
      <slot></slot>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfimClick">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { defineProps, ref, watch, defineExpose } from 'vue'
import CkyForm from '@/base-ui/form'
import { useStore } from '@/store'

const props = defineProps({
  modalConfig: {
    type: Object,
    required: true
  },
  defaultInfo: {
    type: Object,
    default: () => ({})
  },
  otherInfo: {
    type: Object,
    default: () => ({})
  },
  pageName: {
    type: String,
    required: true
  }
})
const store = useStore()

const dialogVisible = ref(false)
const formData = ref<any>({})
watch(
  () => props.defaultInfo,
  (newValue) => {
    for (const item of props.modalConfig.formItems) {
      formData.value[`${item.field}`] = newValue[`${item.field}`]
    }
  }
)

const handleConfimClick = () => {
  dialogVisible.value = false
  if (Object.keys(props.defaultInfo).length) {
    store.dispatch('system/editPageDataAction', {
      pageName: props.pageName,
      newData: { ...formData.value, ...props.otherInfo },
      id: props.defaultInfo.id
    })
  } else {
    store.dispatch('system/createPageDataAction', {
      pageName: props.pageName,
      newData: { ...formData.value, departmentId: 3, ...props.otherInfo }
    })
  }
}

defineExpose({
  dialogVisible
})
</script>

<style></style>
